package com.duoec.dw.lineage.service.impl.analyser.alert;

import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropColumnItem;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.DdlChangeItemDto;
import com.duoec.dw.lineage.enums.DdlChangeTypeEnum;
import com.duoec.dw.lineage.service.AlterTableItemAnalyser;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author xuwenzhen
 */
@Service
public class AlterTableDropColumnItemAnalyser implements AlterTableItemAnalyser<SQLAlterTableDropColumnItem> {
    /**
     * 获取处理类型
     *
     * @return SQLAlterTableItem子类
     */
    @Override
    public Class<SQLAlterTableDropColumnItem> getType() {
        return SQLAlterTableDropColumnItem.class;
    }

    /**
     * 解析变更条目，返回影响数仓的变更
     *
     * @param item 一条变更条目
     * @return 影响数仓的变更，如果没有影响则返回null
     */
    @Override
    public List<DdlChangeItemDto> analyse(SQLAlterTableDropColumnItem item) {
        List<SQLName> columns = item.getColumns();
        if (CollectionUtils.isEmpty(columns)) {
            return null;
        }
        List<DdlChangeItemDto> ddlChangeList = Lists.newArrayList();
        columns.forEach(column -> {
            DdlChangeItemDto ddlChange = new DdlChangeItemDto();
            ddlChange.setFieldName(AnalyserUtils.formatFieldName(column.getSimpleName()));
            ddlChange.setChangeType(DdlChangeTypeEnum.DROP_COLUMN.getType());
            ddlChangeList.add(ddlChange);
        });

        return ddlChangeList;
    }
}
